package com.cet6.controller;

import com.cet6.common.Result;
import com.cet6.dto.DailyStudyProgressDTO;
import com.cet6.dto.DailyWordDTO;
import com.cet6.entity.DailyTask;
import com.cet6.service.DailyStudyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.List;

@RestController
@RequestMapping("/api")
public class DailyStudyController {
    
    @Autowired
    private DailyStudyService dailyStudyService;
    
    /**
     * 获取今日推荐单词
     * @param userId 用户ID（从请求头获取）
     * @return 今日推荐单词列表
     */
    @GetMapping("/words/daily")
    public Result<List<DailyWordDTO>> getDailyWords(@RequestHeader("user-id") Long userId) {
        try {
            if (userId == null || userId <= 0) {
                return Result.error(400, "用户ID不能为空或无效");
            }
            
            List<DailyWordDTO> dailyWords = dailyStudyService.getDailyWords(userId);
            return Result.success("获取今日推荐单词成功", dailyWords);
        } catch (Exception e) {
            return Result.error("获取今日推荐单词失败：" + e.getMessage());
        }
    }
    
    /**
     * 提交每日学习进度
     * @param progressDTO 学习进度数据
     * @return 操作结果
     */
    @PostMapping("/study-records/daily")
    public Result<String> submitDailyProgress(@RequestBody DailyStudyProgressDTO progressDTO) {
        try {
            // 参数验证
            if (progressDTO.getUserId() == null || progressDTO.getUserId() <= 0) {
                return Result.error(400, "用户ID不能为空或无效");
            }
            if (progressDTO.getWordId() == null || progressDTO.getWordId() <= 0) {
                return Result.error(400, "单词ID不能为空或无效");
            }
            if (progressDTO.getResult() == null || (progressDTO.getResult() != 0 && progressDTO.getResult() != 1)) {
                return Result.error(400, "学习结果无效，应为0或1");
            }
            if (progressDTO.getStudyType() == null || (progressDTO.getStudyType() != 0 && progressDTO.getStudyType() != 1)) {
                return Result.error(400, "学习类型无效，应为0或1");
            }
            
            boolean success = dailyStudyService.submitDailyProgress(progressDTO);
            if (success) {
                return Result.success("学习进度提交成功");
            } else {
                return Result.error("学习进度提交失败");
            }
        } catch (Exception e) {
            return Result.error("提交学习进度失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取用户今日任务
     * @param userId 用户ID（从请求头获取）
     * @param date 任务日期（可选，默认为今天）
     * @return 每日任务信息
     */
    @GetMapping("/daily-tasks")
    public Result<DailyTask> getDailyTask(@RequestHeader("user-id") Long userId,
                                        @RequestParam(required = false) String date) {
        try {
            if (userId == null || userId <= 0) {
                return Result.error(400, "用户ID不能为空或无效");
            }
            
            LocalDate taskDate = date != null ? LocalDate.parse(date) : LocalDate.now();
            DailyTask dailyTask = dailyStudyService.getDailyTask(userId, taskDate);
            
            if (dailyTask == null) {
                return Result.error(404, "未找到该日期的学习任务");
            }
            
            return Result.success("获取每日任务成功", dailyTask);
        } catch (Exception e) {
            return Result.error("获取每日任务失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取用户学习统计
     * @param userId 用户ID（从请求头获取）
     * @return 学习统计信息
     */
    @GetMapping("/study-stats")
    public Result<Object> getStudyStats(@RequestHeader("user-id") Long userId) {
        try {
            if (userId == null || userId <= 0) {
                return Result.error(400, "用户ID不能为空或无效");
            }
            
            // 获取今日任务
            DailyTask todayTask = dailyStudyService.getDailyTask(userId, LocalDate.now());
            
            // 构建统计信息
            final DailyTask finalTodayTask = todayTask;
            Object stats = new Object() {
                public final DailyTask todayTask = finalTodayTask;
                public final String message = "学习统计获取成功";
            };
            
            return Result.success("获取学习统计成功", stats);
        } catch (Exception e) {
            return Result.error("获取学习统计失败：" + e.getMessage());
        }
    }
}
